package com.cskaoyan.catmall.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.InputStream;

/**
 * @Author: 逍遥子
 * @Date: 2022/01/08/17:41
 * @Description:
 */
public class FIleUploadUtil {

    public static String upload(InputStream inputStream){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        UploadManager uploadManager = new UploadManager(cfg);

        // 上传凭证
        String accessKey = "Uxv7S8cYoVvzznmVcWegxzV-ihWvqjDR5iV3Joph";
        String secretKey = "jM_VBuv9TODxZ0M1F5hPUtYkyGhjutKQXzRSe93Q";
        String bucket = "javastudytest";

        // 图片资源路径
        //String localFilePath = path;

        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(inputStream, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return "http://r4ilk88q6.hn-bkt.clouddn.com/" + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {

            }
        }
        return null;
    }
}
